<?php

/**
 * 标签表
 * File Name：TagsModel.php
 * File Encoding：UTF-8
 * File New Time：2014-9-9 11:29:43
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class TagsModel extends BaseModel {

    public function tableName() {
        return '{{tags}}';
    }

    public function rules() {
        return array(
            array('tag', 'required', 'message' => '标签不能为空！'),
            array('tag', 'unique', 'message' => '该标签已经存在，不能重复添加！'),
            array('style,usetimes,start_sum,lastusetime,hits,lasthittime,listorder', 'safe'),
        );
    }

    //数据保存前操作
    protected function beforeSave() {
        //是否新增
        if ($this->isNewRecord) {
            $time = time();
            //添加时间
            $this->usetimes = 1;
            $this->lastusetime = $this->lasthittime = $time;
            $this->hits = 0;
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 添加tags
     * @param type $tagname tags名称 可以是数组
     * @param type $goods_id 商品主键goods_id
     * @param type $cat_id 栏目Id
     * @param type $data 附加数据
     * @return boolean
     */
    public function addTag($tagname, $goods_id, $cat_id, $data = array()) {
        if (!$tagname || !$goods_id || !$cat_id) {
            return false;
        }
        $TagsContentModel = TagsContentModel::model();
        if (is_array($tagname)) {
            foreach ($tagname as $v) {
                if (empty($v)) {
                    continue;
                }
                $info = $this->find($this->where(array("tag" => $v)));
                if (!empty($info)) {
                    $tagid = $info->tagid;
                    $info->usetimes += 1;
                    if (!$info->save()) {
                        continue;
                    }
                } else {
                    unset($this->tagid);
                    $this->tag = trim($v);
                    $this->usetimes = 1;
                    $this->setIsNewRecord(true);
                    if (!$this->save()) {
                        continue;
                    }
                    $tagid = $this->primaryKey;
                }
                $newData = array(
                    'tagid' => $tagid,
                    'tag' => $v,
                    'goods_name' => $data['goods_name'],
                    'goods_id' => $goods_id,
                    'start_time' => $data['start_time'],
                    'end_time' => $data['end_time'],
                    'cat_id' => $cat_id,
                );
                $TagsContentModel->attributes = $newData;
                $TagsContentModel->setIsNewRecord(true);
                $TagsContentModel->save();
                unset($info, $newData);
            }
            return true;
        } else {
            if (empty($tagname)) {
                return false;
            }
            //检查是否存在
            $info = $this->find($this->where(array("tag" => $tagname)));
            if (!empty($info)) {
                $tagid = $info->tagid;
                $info->usetimes += 1;
                if (!$info->save()) {
                    return false;
                }
            } else {
                $this->tag = trim($tagname);
                $this->usetimes = 1;
                $this->setIsNewRecord(true);
                if (!$this->save()) {
                    return false;
                }
                $tagid = $this->primaryKey;
            }
            $newData = array(
                'tagid' => $tagid,
                'tag' => $tagname,
                'goods_name' => $data['goods_name'],
                'goods_id' => $goods_id,
                'start_time' => $data['start_time'],
                'end_time' => $data['end_time'],
                'cat_id' => $cat_id,
            );
            $TagsContentModel->attributes = $newData;
            $TagsContentModel->setIsNewRecord(true);
            if ($TagsContentModel->save()) {
                return true;
            }
            return false;
        }
    }

    /**
     * 更新信息tag
     * @param array $tagname 标签
     * @param type $goods_id 商品主键ID
     * @param type $data 其他数据
     * @return boolean
     */
    public function updata(array $tagname, $goods_id, $cat_id, $data = array()) {
        if (!$tagname || !$goods_id) {
            return false;
        }
        $db_tags_content = TagsContentModel::model();
        $tags = $db_tags_content->findAll($this->where(array(
                    "goods_id" => $goods_id,
        )));
        foreach ($tags as $key => $value) {
            //如果在新的关键字数组找不到，说明已经去除
            if (!in_array($value['tag'], $tagname)) {
                //删除不存在的tag
                $this->deleteTagName($value['tag'], $goods_id);
            } else {
                //更新
                $db_tags_content->updateAll(array(
                    'goods_name' => $data['goods_name'],
                    'cat_id' => $cat_id,
                    'start_time' => $data['start_time'],
                    'end_time' => $data['end_time'],
                        ), $this->where(array("goods_id" => $goods_id,)));
                foreach ($tagname as $k => $v) {
                    if ($value['tag'] == $v) {
                        unset($tagname[$k]);
                    }
                }
            }
        }
        //新增的tags
        if (count($tagname) > 0) {
            $this->addTag($tagname, $goods_id, $cat_id, $data);
        }
        return true;
    }

    /**
     * 根据信息id删除全部的tags记录
     * @param type $goods_id
     * @return boolean
     */
    public function deleteAll($goods_id) {
        if (!$goods_id) {
            return false;
        }
        $db_tags_content = TagsContentModel::model();
        $where = array('goods_id' => $goods_id);
        //取得对应tag数据
        $tagslist = $db_tags_content->findAll($db_tags_content->where($where));
        if (empty($tagslist)) {
            return true;
        }
        //全部-1
        foreach ($tagslist as $k => $value) {
            $info = $this->find($this->where(array("tag" => $value['tag'])));
            if (!empty($info) && $info->usetimes) {
                $info->usetimes -= 1;
                $info->save();
            }
        }
        //删除tags数据
        $db_tags_content->deleteAll($db_tags_content->where($where));
        return true;
    }

    /**
     * 删除tag
     * @param type $tagname tag
     * @param type $goods_id 商品主键ID
     * @return boolean
     */
    public function deleteTagName($tagname, $goods_id) {
        if (!$goods_id || !$tagname) {
            return false;
        }
        $r = $this->find($this->where(array("tag" => $tagname)));
        if ($r) {
            if ($r['usetimes'] > 0) {
                $r->usetimes -= 1;
                $r->save();
            }
            //删除tags数据
            TagsContentModel::model()->deleteAll($this->where(array("tag" => $r['tag'], 'goods_id' => $goods_id)));
            return true;
        }
        return false;
    }

    /**
     * 返回首页需要显示的tags列表
     * @return array
     */
    public function getHomeTagsList() {
        $key = 'TagsModel_getHomeTagsList';
        $cache = Yii::app()->cache->get($key);
        if (!empty($cache)) {
            return $cache;
        }
        $where = array('start_sum' => array('GT', 10), 'order' => 'start_sum desc', 'limit' => 5);
        $data = $this->findAll($this->where($where));
        if (empty($data)) {
            return array();
        }
        Yii::app()->cache->set($key, $data, 600);
        return $data;
    }

    /**
     * 根据各类名显示热门tags列表
     * @param type $cat_id
     * @return array
     */
    public function getCatTagsList($cat_id) {
        $key = 'TagsModel_getCatTagsList_' . $cat_id;
        $cache = Yii::app()->cache->get($key);
        if (!empty($cache)) {
            return $cache;
        }
        $time = time();
        $where = array(
            'cat_id' => $cat_id,
            'start_time' => array('LT', $time),
            'end_time' => array('EGT', $time),
            'group' => 'tagid',
        );
        $data = $this->findAll($this->where($where));
        if (empty($data)) {
            return array();
        }
        Yii::app()->cache->set($key, $data, 600);
        return $data;
    }

}
